#!/usr/bin/env python3

import gt
import os
import random

#  全局变量的定义
#  画布大小
ROW, COL = 15, 60
#  球的属性描述
x, y, x_inc, y_inc, r, color, ch = 3, 3, 1, 1, 3, 31, '@'
#  画布载体
convas = None

def createConvas(r, c):
    """
    画布创建
    """
    convas = list(range(r))
    for x in convas:
        convas[x] = list(range(c))
    return convas

def initConvas(convas, row, col):
    """
    画布初始化
    """
    for r in range(row):
        for c in range(col):
            if r == 0 or c == 0 or r == row - 1 or c == col - 1:
                convas[r][c] = '#'
            else:
                convas[r][c] = ' '
    return convas

#  def initConvas(row, col):
    #  """
    #  创建画布并且初始化
    #  """
    #  convas = []
    #  for r in range(row):
        #  convas.append([])
        #  for c in range(col):
            #  if r == 0 or c == 0 or r == row - 1 or c == col - 1:
                #  convas[r].append('#')
            #  else:
                #  convas[r].append(' ')
    #  return convas

def showConvas(convas, row, col, color, ch):
    """
    刷新画布
    """
    print("\033[1;1H", end='', flush=True)
    for r in range(row):
        for c in range(col):
            if convas[r][c] == ch:
                print("\033[%dm%c\033[0m" % (color, ch), end='', flush=True)
            else:
                print(convas[r][c], end='')
        print()

def draw(convas, row, col, x, y, r, ch):
    """
    在画布上作画
    """
    for i in range(y, y + r):
        for j in range(x, x + r):
            if i > ROW - 1 or j > COL - 1 or i < 0 or j < 0:
                continue
            convas[i][j] = ch

def ball_init(row, col):
    """
    弹球程序的初始化操作
    """
    print("\033[2J\033[?25l", end='', flush=True)
    gt.init()
    return createConvas(row, col)

def ball_exit(row):
    """
    弹球程序退出终端还原操作
    """
    print("\033[%d;1H\033[?25h" % (row + 2), end='', flush=True)
    gt.exit()
    os._exit(0)

def move():
    """
    弹球运动控制
    """
    global x, y, x_inc, y_inc, color

    if x <= 0 or x + r > COL - 1:
        x_inc *= -1
        color = random.randint(30, 37)

    if y <= 0 or y + r > ROW - 1:
        y_inc *= -1
        color = random.randint(30, 37)

    x += x_inc
    y += y_inc

def ball():
    """
    弹球动画流程
    """
    initConvas(convas, ROW, COL)
    draw(convas, ROW, COL, x, y, r, ch)
    move()
    showConvas(convas, ROW, COL, color, ch)

    #  下一次动画显示的延时设置
    gt.run(ball, 0.1)

def keyHandle():
    global color, x_inc, y_inc

    while True:
        ch = gt.get()
        if ch == 'q' or ord(ch) == 27:
            break
        elif ch == 'c':
            color = random.randint(30, 37)
        elif ch == 'w':
            y_inc = -1
        elif ch == 's':
            y_inc = 1
        elif ch == 'a':
            x_inc = -1
        elif ch == 'd':
            x_inc = 1

if __name__ == '__main__':
    convas = ball_init(ROW, COL)
    gt.run(ball)
    keyHandle()
    ball_exit(ROW)


